package com.work.module_base.utils;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;


import androidx.core.content.FileProvider;

import com.work.module_base.base.AndroidOPermissionActivity;

import java.io.File;


/**
 * author：WangZhan
 * data: 2017/11/1 11:23
 * version: 1.0.0
 * explain:版本更新
 */

public class VersionUpdateUtil {
    public static VersionUpdateUtil versionUpdate = new VersionUpdateUtil();
    static File downloadFile;

    public static VersionUpdateUtil newInstance() {
        return versionUpdate;
    }

    private VersionUpdateUtil() {
    }

    public static void gotoUpdate(Context context, String url) {
        UIUtils.showToast("已放入后台下载新版本!");
        DownloadManager downloadManager = (DownloadManager) context.getSystemService(context.DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.setMimeType("application/vnd.android.package-archive");

        downloadFile = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "wywl.apk");

        request.setDestinationUri(Uri.fromFile(downloadFile));
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setTitle("微羽万联");
        request.setVisibleInDownloadsUi(true);

        long downloadId = downloadManager.enqueue(request);
        DownCompleteReceiver downCompleteReceiver = new DownCompleteReceiver(downloadId);
        context.registerReceiver(downCompleteReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

    public void createDialogUpdate(final Context context, final String url, String upContent) {
        AlertDialog.Builder alert = new AlertDialog.Builder(context);
        alert.setTitle("更新提示")
                .setMessage(upContent)
                .setCancelable(false).setNeutralButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                UIUtils.showToast("已放入后台下载新版本");
                gotoUpdate(context, url);
                dialog.dismiss();
            }
        });
        alert.create().show();
    }


    public static class DownCompleteReceiver extends BroadcastReceiver {
        long enqueueId;

        public DownCompleteReceiver(long enqueueId) {
            this.enqueueId = enqueueId;
        }

        @Override
        public void onReceive(final Context context, final Intent intent) {

            DownloadManager dm = (DownloadManager) context.getSystemService(context.DOWNLOAD_SERVICE);
            long id = intent.getExtras().getLong(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if (enqueueId != id) {
                return;
            }

            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(enqueueId);

            Cursor c = dm.query(query);

            if (c != null && c.moveToFirst()) {
                int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
                // 下载失败也会返回这个广播，所以要判断下是否真的下载成功
                if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
                    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                        final Uri uri = FileProvider.getUriForFile(context, "com.weiyu.wywl.wygateway.fileprovider", downloadFile);
                        final Intent installIntent = new Intent(Intent.ACTION_VIEW);
                        installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        installIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        installIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                        installIntent.setDataAndType(uri, "application/vnd.android.package-archive");
                        // 兼容Android 8.0
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            //先获取是否有安装未知来源应用的权限
                            boolean haveInstallPermission = context.getPackageManager().canRequestPackageInstalls();
                            if (!haveInstallPermission) {
                                UIUtils.showToast("没有权限");
                                //没有权限
                                // 弹窗，并去设置页面授权
                                final AndroidOInstallPermissionListener listener = new AndroidOInstallPermissionListener() {
                                    @Override
                                    public void permissionSuccess() {
                                        context.startActivity(installIntent);
                                    }

                                    @Override
                                    public void permissionFail() {
                                        UIUtils.showToast("授权失败，无法安装应用");
                                    }
                                };
                                AndroidOPermissionActivity.sListener = listener;
                                Intent intent1 = new Intent(context, AndroidOPermissionActivity.class);
                                context.startActivity(intent1);
                            } else {
                                context.startActivity(installIntent);
                            }
                        } else {
                            context.startActivity(installIntent);
                        }
                    } else {
                        // 获取下载好的 apk 路径
                        @SuppressLint("Range") String uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
                        // 提示用户安装
                        installAPP(Uri.parse("file://" + uriString), context);
                    }
                }
                c.close();
            }
        }

        private void installAPP(Uri data, Context context) {
            Intent promptInstall = new Intent(Intent.ACTION_VIEW)
                    .setDataAndType(data, "application/vnd.android.package-archive");
            // FLAG_ACTIVITY_NEW_TASK 可以保证安装成功时可以正常打开 app
            promptInstall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(promptInstall);
        }
    }

    public interface AndroidOInstallPermissionListener {
        void permissionSuccess();

        void permissionFail();
    }
}

